package com.gitee.wsl.jvm.ext

import java.awt.Desktop
import java.net.URI
import java.util.concurrent.TimeUnit

object RuntimeExt {

    fun getJvmVersion(): Int {
        var version = System.getProperty("java.version")
        if (version.startsWith("1.")) {
            version = version.substring(2, 3)
        } else {
            val dot = version.indexOf(".")
            if (dot != -1) {
                version = version.substring(0, dot)
            }
        }
        version = version.substringBefore("-")
        //version = substringBefore(version, "-")
        return version.toInt()
    }

    fun isRunningFromNestedJar(): Boolean {
        return Runtime::class.java.protectionDomain?.codeSource?.location
            .toString().split("!".toRegex()).dropLastWhile { it.isEmpty() }
            .toTypedArray().size > 1
    }

    /**
     * this helper function is here to execute a command and waits for the process to finish and return the result based on exit code
     * @param command the command
     * @param waitFor maximum time allowed process finish ( in milliseconds )
     * @return `true` when process exits with `0` exit code, `false` if the process fails with non-zero exit code or execution time exceeds the [waitFor]
     */
    fun execAndWait(
        command: Array<String>,
        waitFor: Long = 2_000,
    ): Boolean {
        return runCatching {
            val p = Runtime.getRuntime().exec(command)
            val exited = p.waitFor(waitFor, TimeUnit.MILLISECONDS)
            if (exited) {
                p.exitValue() == 0
            } else {
                false
            }
        }.getOrElse { false }
    }

    fun openUrl(url: String) {
        kotlin.runCatching {
            val desktop = Desktop.getDesktop()
            if (desktop.isSupported(Desktop.Action.BROWSE)) {
                desktop.browse(URI(url))
            }
        }
    }
}